#! /usr/bin/env python
# coding=utf-8
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# Author: senlin
# Create: 2022-02-14
# ******************************************************************************/

import re
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from src.libs.logger import logger
from src.common.loadconf import local_conf

class SendEmail(object):
    """
    """

    def  __init__(self, message, to_email, sender='163_sender'):
        """
        @description :
        -----------
        @param :
        -----------
        @returns :
        -----------
        """
        self._message = message
        self.sender = dict(local_conf.conf.items(sender))
        self.cc = dict(local_conf.conf.items("cc"))
        self.to = dict(local_conf.conf.items("to"))
        self.to_email = to_email

    def notify_all_respon_person(self):
        """
        notice all packages to person
        """
        
        if self._send_email(self._message):
            logger.info("send email succeed !")
            return True
        else:
            logger.error(f"send email failed!")
            return False
    
    def _send_email(self, message):
        """
        send a email

        args:
            message: Message body
        returns:
            True: send email normally
            False: Abnormal email sending feedback
        """
        sender_email = self.sender.get('email')
        sender_email_pass = self.sender.get('pass')
        cc_emails = self.cc.get('email').split(',')
        to_emails = self.to.get('email').split(',')
        # to_emails = self._check_email()

        msg = MIMEText(message, 'html')
        msg['Subject'] = Header("[OBS Package Version Difference Notice]", "utf-8")
        msg["From"] = Header(self.sender.get('email'))
        msg["To"] = Header(";".join(to_emails))
        msg["Cc"] = Header(";".join(cc_emails))

        try:
            server = smtplib.SMTP_SSL(self.sender.get('smtp_server'))
            server.login(sender_email, sender_email_pass)
            server.sendmail(sender_email, to_emails + cc_emails, msg.as_string())
            server.quit()
            return True
        except smtplib.SMTPException as err:
            logger.error(f"Abnormal email sending feedback: {err}")
            return False
            
    def _check_email(self):
        """
        Verify and keep the legal email address

        returns:
            valid_email: legal email address
        """
        valid_email = set()
        for origin_email in self.to_email:
            try:
                regular = re.compile(r'[0-9a-zA-Z\.]+@[0-9a-zA-Z\.]+[com, org]')
                email = re.findall(regular, origin_email)[0]
                if email:
                    valid_email.add(email)
            except IndexError as e:
                logger.error(f"analyse developer for {email} failed")
        return list(valid_email)

